package cn.li.org.servcie.impl;

import cn.li.basic.service.impl.BaseServiceImpl;
import cn.li.basic.util.PageList;
import cn.li.org.domain.Department;
import cn.li.org.mapper.DepartmentMapper;
import cn.li.org.query.DepartmentQuery;
import cn.li.org.servcie.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service//开启扫描
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)//开启事务
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper mapper;

    @Override
    @Transactional//开启事务
    public void add(Department department) {
        mapper.save(department);//返回自增ID
        this.update(department);
    }//添加

    @Override
    @Transactional//开启事务
    public void update(Department department) {
        //这里不仅需要保存数据，还需要保存ditPath 后期用来做上级部门回显
        String dirPath = "";
        if(department.getParent() == null){
            //1.如果新增的是定顶级 直接保存自己的自增id  /自己的id
            dirPath = "/"+department.getId();
        }else{
            //2.如果不是顶级  找出父亲的ditPath + /自己的id
            Department parent = mapper.loadById(department.getParent().getId());
            dirPath = parent.getDirPath() + "/"+department.getId();
        }
        department.setDirPath(dirPath);
        mapper.update(department);
    }//修改


    @Override
    public List<Department> queryTree() {
        //        *  方案四：必须掌握
//        *    1.一次性查询出所有数据，放到内存 all
        List<Department> allDepts = mapper.loadAll();
        //为了下面内层嵌套循环，查询父亲方便，我们这里把所有数据，抽成map<部门ID，部门对象>
        /*Map<Long, Department> allDeptMap =
                allDepts.stream().collect(Collectors.toMap(Department::getId, dept -> dept));*/
        HashMap<Long, Department> allDeptMap = new HashMap<>();
        for (Department tmp : allDepts) {
            allDeptMap.put(tmp.getId(),tmp);
        }
        List<Department> firstDepts = new ArrayList<>();
        for (Department deptTmp : allDepts) {
            if(deptTmp.getParent_id() == null){//代表是顶级
//        *    2.从所有数据中找出第一层级 firstDepartment   我们需要返回的数据
                firstDepts.add(deptTmp);
            }else{
                // 可能是第二、第三、第四......
//        *    3.只要不是第一层级的，找自己的上级，并将自己放入上级的children中
                Department parent = allDeptMap.get(deptTmp.getParent_id());
                if(parent != null){
                    parent.getChildren().add(deptTmp);
                }
            }
        }
        return firstDepts;
    }
}
